import json
import os
from packaging import version

def process_packages():
    # 获取 JSON 文件路径
    current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    json_path = os.path.join(current_dir, 'data', 'all_packages.json')
    
    # 读取 JSON 文件
    with open(json_path, 'r', encoding='utf-8') as f:
        packages = json.load(f)

    # 创建包名到版本的映射
    package_versions = {}
    for pkg in packages:
        name = pkg['name']
        ver = pkg['version']
        status = pkg['status']
        
        # 如果包名不存在或者新版本更高，则更新
        if name not in package_versions or \
           version.parse(ver) > version.parse(package_versions[name]['version']):
            package_versions[name] = {
                'version': ver,
                'status': status
            }

    # 生成新的包列表
    new_packages = [
        {
            'name': name,
            'version': info['version'],
            'status': info['status']
        }
        for name, info in package_versions.items()
    ]

    # 按包名排序
    new_packages.sort(key=lambda x: x['name'])

    # 写回文件
    with open(json_path, 'w', encoding='utf-8') as f:
        json.dump(new_packages, f, indent=2, ensure_ascii=False)

    return len(packages) - len(new_packages)

if __name__ == '__main__':
    try:
        removed_count = process_packages()
        print(f'成功处理包版本信息：')
        print(f'- 删除了 {removed_count} 个重复的包版本')
        print(f'- 保留了每个包的最高版本')
        print('处理完成！')
    except Exception as e:
        print(f'处理过程中发生错误：{str(e)}')